<template>
  <div class="admin-layout">
    <el-container class="layout-container">
      <!-- 顶部导航栏 -->
      <el-header class="header">
        <div class="logo">
          <span>思不罔后台管理系统</span>
        </div>

        <div class="home-link">
          <el-button type="text" @click="goToHome">
            <el-icon><HomeFilled /></el-icon>
            <span>返回首页</span>
          </el-button>
        </div>

        <div class="user-info">
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-avatar :size="36" :src="avatarUrl" />
              <span class="username">{{ adminName }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleProfile">个人中心</el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏菜单 -->
        <el-aside width="200px" class="aside">
          <el-menu
              router
              :default-active="activeMenu"
              class="sidebar-menu"
              @select="handleMenuSelect"
          >
            <el-menu-item index="/admin/manage/questions">
              <el-icon><Document /></el-icon>
              <span>题目管理</span>
            </el-menu-item>

            <el-menu-item index="/admin/manage/majors-categories">
              <el-icon><Folder /></el-icon>
              <span>专业与分类管理</span>
            </el-menu-item>

            <el-menu-item index="/admin/manage/comments">
              <el-icon><ChatLineRound /></el-icon>
              <span>评论与社区管理</span>
            </el-menu-item>

            <el-menu-item v-if="false" index="/admin/manage/">
              <el-icon><EditPen /></el-icon>
              <span>学习建议管理/未实现</span>
            </el-menu-item>

            <el-menu-item v-if="false" index="/admin/">
              <el-icon><DataAnalysis /></el-icon>
              <span>用户学习行为管理/未实现</span>
            </el-menu-item>

            <el-menu-item v-if="false" index="/admin/">
              <el-icon><DataBoard /></el-icon>
              <span>题目统计看板/未实现</span>
            </el-menu-item>

            <el-menu-item index="/admin/manage/users">
              <el-icon><User /></el-icon>
              <span>用户管理</span>
            </el-menu-item>

            <el-menu-item v-if="false" index="/admin/manage/settings">
              <el-icon><Setting /></el-icon>
              <span>系统设置/未实现</span>
            </el-menu-item>

          </el-menu>
        </el-aside>

        <!-- 主内容区 - 直接显示路由内容 -->
        <el-main class="main-content">
          <div class="content-container">
<!--            <router-view v-slot="{ Component }">-->
<!--              <transition name="fade" mode="out-in">-->
<!--                <component :is="Component" :key="$route.fullPath" />-->
<!--              </transition>-->
<!--            </router-view>-->
<!--            强制路由组件重新渲染-->
            <router-view v-slot="{ Component }">
              <component :is="Component" :key="$route.fullPath" />
            </router-view>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document, Folder, User, Setting,HomeFilled,
  DataAnalysis, ChatLineRound, DataBoard,EditPen
} from '@element-plus/icons-vue'
import { useUserStore } from '@/store/useUserstore'
import axios from "@/api/server";
import jwtDecode from 'jwt-decode';

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 用户信息
const adminName = computed(() => {
  return userStore.userInfo.username || '管理员'
})

const avatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 菜单选择处理
const handleMenuSelect = (index) => {
  router.push(index)
}

// 返回首页
const goToHome = () => {
  router.push('/home');
};

// 个人中心
const handleProfile = () => {
  router.push('/personal')
}

// 退出登录
const handleLogout = async () => {
  try {
    await axios.post('/users/logout'); // 会自动带上 Bearer token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    ElMessage.success('退出成功');
    await router.push('/');
  } catch (error) {
    console.error('退出失败：', error);
    ElMessage.error('退出失败');
  }
};

// 页面加载时验证管理员权限
onMounted(() => {
  // 检查用户是否登录
  let token = userStore.token;
  if (!token) {
    token = localStorage.getItem('token');
    if (token) {
      userStore.setToken(token);
    } else {
      router.push('/login');
      return;
    }
  }

  // 如果userInfo为空，尝试从token解析
  if (!userStore.userInfo || Object.keys(userStore.userInfo).length === 0) {
    try {
      const decodedToken = jwtDecode(token);
      userStore.setUserInfo(decodedToken);
    } catch (e) {
      console.error('Token解析失败:', e);
      router.push('/login');
      return;
    }
  }

  // 检查是否为管理员
  if (userStore.userInfo.isAdmin !== true) {
    ElMessage.warning('您没有管理员权限');
    router.push('/home');
  }
});
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  overflow: hidden;
}

.layout-container {
  height: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #2c3e50;
  color: #fff;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.logo {
  font-size: 18px;
  font-weight: bold;
}

.home-link {
  display: flex;
  align-items: center;
  margin-left: auto;
  margin-right: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin-left: 10px;
  font-size: 14px;
}

.aside {
  background-color: #304156;
  height: calc(100vh - 60px);
}

.sidebar-menu {
  border-right: none;
  background-color: #304156;
}

.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: #bfcbd9;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: #263445 !important;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background-color: #1890ff !important;
  color: #fff;
}

.main-content {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px);
}

.content-container {
  flex: 1;
  padding: 15px;
  overflow: auto;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #fff;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>